// async function sleep(timeout) {
//     return new Promise((resolve, reject) => {
//         setTimeout(() => {
//             resolve();
//         }, timeout);
//     });
// }
// var isChecked = false;
// var isReply = false;
// var isComment = false;
// var nickName = null;
// startCheck();
// async function startCheck() {
//     let url = location.href;
//     if (url.indexOf('https://zs.kwaixiaodian.com/page/helper') != 0) {
//         console.log('网址错误');
//         return;
//     }
//     while (true) {
//         let btnList = document.querySelectorAll('button.ant-btn');
//         if (btnList.length >= 2) {
//             if (btnList[1].innerText == '回到旧版') {
//                 btnList[1].click();
//                 return;
//             }
//             else if (btnList[1].innerText == '进入新版') {
//                 isChecked = true;
//                 break;
//             }
//         }
//         await sleep(100);
//     }
//     nickName = document.querySelector('div[class^=nickname]').innerText;
//     startReply();
// }
// //开始回复
// async function startReply() {
//     if (!isChecked)
//         return;

//     console.log('监听回复');
//     //开始监听评论
//     let lastCommentID = window.localStorage.getItem('commentID');
//     //开始监测聊天窗口的插入情况
//     window.replyObserver = new MutationObserver(function (mutationsList, observer) {
//         // 对变动进行处理
//         for (let mutation of mutationsList) {
//             if (mutation.type === 'childList') {
//                 mutation.addedNodes.forEach((value) => {
//                     //首先查看是不是自己发出的，如果是自己发出的，就不管了
//                     let userName = value.querySelector('span[class^=username]').innerText;
//                     if (nickName == userName)
//                         return;
//                     //如果不相同的话，则需要匹配回复
//                     let reply = value.querySelector('span[class^=replied-content]').innerText;
//                     //查询是否有对应的内容
//                     console.log(userName, reply);
//                 });
//             }
//         }
//     });
//     const config = { childList: true };
//     window.replyObserver.observe(document.querySelector('div.ReactVirtualized__Grid__innerScrollContainer'), config);
// }


// function DWHelper() {
//     var isChecked = false;
//     var isReply = false;
//     var isComment = false;
//     var nickName = null;
//     var userID = null;
//     var liveStreamID = null;

//     var KTRACE_STR_HEADER_KEY = "ktrace-str", KTRACE_CONTEXT = "ktrace-context", MAX_SPAN_LENGTH = 1e3, MAX_TAG_LENGTH = 100, MAX_LOG_LENGTH = 10, VERSION$1 = 1;
//     var separator = "."
//         , distributeIdLen = 5
//         , serviceNameSlice = 8
//         , counter = 1e3;
//     function getRandomString(v, l) {
//         for (var e = []; l--;) {
//             var a = Math.floor(Math.random() * v.length);
//             e.push(v[a])
//         }
//         return e.join("")
//     }
//     function parseServiceNameToNumber(v) {
//         return Array.from(v.slice(-serviceNameSlice)).map(function (l) {
//             return l.toUpperCase().charCodeAt(0)
//         }).join("")
//     }
//     function base64Encode(v) {
//         try {
//             return btoa(v)
//         } catch (l) {
//             return v
//         }
//     }
//     function asyGet(url) {
//         return new Promise((resolve, reject) => {
//             var xhr = new XMLHttpRequest();
//             xhr.open("GET", url, true);
//             xhr.withCredentials = true;
//             xhr.setRequestHeader('Content-type', 'application/json;charset=UTF-8');
//             xhr.onreadystatechange = function () {
//                 if (xhr.readyState == 4)
//                     resolve({
//                         status: xhr.status,
//                         data: xhr.responseText
//                     });
//             }
//             xhr.send();
//         });
//     }
//     function asyPost(url, data) {
//         return new Promise((resolve, reject) => {
//             var xhr = new XMLHttpRequest();
//             xhr.open("POST", url, true);
//             xhr.withCredentials = true;
//             xhr.setRequestHeader('Content-type', 'application/json;charset=UTF-8');
//             xhr.onreadystatechange = function () {
//                 if (xhr.readyState == 4)
//                     resolve({
//                         status: xhr.status,
//                         data: xhr.responseText
//                     });
//             }
//             if (typeof data != 'string')
//                 xhr.send(JSON.stringify(data));
//             else
//                 xhr.send(data);
//         });
//     };
//     function createDistributeId(v) {
//         console.log(counter);
//         var l = ["" + VERSION$1, "" + parseServiceNameToNumber(v), "" + getRandomString("123456789", 8), "" + Date.now(), "" + counter++];
//         return base64Encode(l.join(separator));
//     }
//     this.initData = async function () {
//         //首先查询用户信息
//         var { status, data } = await asyPost('https://zs.kwaixiaodian.com/rest/pc/live/assistant/sys/info', '');
//         if (status != 200)
//             return;
//         data = JSON.parse(data);
//         userID = data.data.userInfo.sellerId;
//         nickName = data.data.userInfo.sellerNick;
//         var { status, data } = await asyPost('https://zs.kwaixiaodian.com/rest/pc/live/assistant/live/current/info', '');
//         if (status != 200)
//             return;
//         data = JSON.parse(data);
//         liveStreamID = data.data.liveStreamId;
//     }
//     this.postReply = async function (commentID, replayContent) {
//         if (!userID || !liveStreamID)
//             return;
//         var data = {
//             liveStreamId: liveStreamID,
//             replyContent: replayContent,
//             commentId: commentID,
//             fromUserId: userID
//         };
//         var { status, data } = await asyPost('https://zs.kwaixiaodian.com/rest/pc/live/assistant/comment/reply', data);
//         if (status != 200)
//             return;

//         { "result": 1, "error_msg": "", "requestId": "725354616530385605" }

//     }
// }

class DWHelper {
    constructor() {
        this.userName = null;
        this.userID = null;
        this.liveStreamID = null;
        this.replyObserver = null;
        this.replyConfig = null;
        this.commentConfig = null;//配置里{contents:[],}
        this.commentTimer = null;
        this.expresses = ["[捂脸]",
            "[玫瑰]",
            "[爱心]",
            "[赞]",
            "[666]",
            "[火]",
            "[点点关注]",
            "[我爱你]",
            "[比心]",
            "[庆祝]",
            "[亲亲]",
            "[礼花]",
            "[狮子]",
            "[吃瓜]",
            "[愉快]",
            "[发]",
            "[龇牙]",
            "[干杯]"
        ];
        this.commentMaxSize = 40;
    };
    asySleep(timeout) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve();
            }, timeout);
        });
    }
    asyGet(url) {
        return new Promise((resolve, reject) => {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", url, true);
            xhr.withCredentials = true;
            xhr.setRequestHeader('Content-type', 'application/json;charset=UTF-8');
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4)
                    resolve({
                        status: xhr.status,
                        data: xhr.responseText
                    });
            }
            xhr.send();
        });
    };
    asyPost(url, data) {
        return new Promise((resolve, reject) => {
            var xhr = new XMLHttpRequest();
            xhr.open("POST", url, true);
            xhr.withCredentials = true;
            xhr.setRequestHeader('Content-type', 'application/json;charset=UTF-8');
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4)
                    resolve({
                        status: xhr.status,
                        data: xhr.responseText
                    });
            }
            if (typeof data != 'string')
                xhr.send(JSON.stringify(data));
            else
                xhr.send(data);
        });
    };
    async initData() {
        let url = location.href;
        if (url.indexOf('https://zs.kwaixiaodian.com/page/helper') != 0) {
            console.log('网址错误');
            return;
        }
        while (true) {
            let btnList = document.querySelectorAll('button.ant-btn');
            if (btnList.length >= 2) {
                if (btnList[1].innerText == '回到旧版') {
                    console.log('回到旧版');
                    btnList[1].click();
                    return;
                }
                else if (btnList[1].innerText == '进入新版') {
                    console.log('进入新版');
                    break;
                }
            }
            await this.asySleep(100);
        }
        //首先查询用户信息
        var { status, data } = await this.asyPost('https://zs.kwaixiaodian.com/rest/pc/live/assistant/sys/info', '');
        if (status != 200) {
            console.log('查询用户信息失败');
            return;
        }
        data = JSON.parse(data);
        this.userID = data.data.userInfo.sellerId;
        this.userName = data.data.userInfo.sellerNick;
        var { status, data } = await this.asyPost('https://zs.kwaixiaodian.com/rest/pc/live/assistant/live/current/info', '');
        if (status != 200) {
            console.log('查询直播间信息失败');
            return;
        }
        data = JSON.parse(data);
        this.liveStreamID = data.data.liveStreamId;
        console.log(this.userID, this.userName, this.liveStreamID);

        while (true) {
            if (document.querySelector('div.ReactVirtualized__Grid__innerScrollContainer'))
                break;
            await this.asySleep(100);
        }
        console.log('初始化完成');
        //去客户端拉配置信息
        window.JSCallInitFinish && window.JSCallInitFinish();
    };
    randExpress() {
        return this.expresses[Math.floor(Math.random() * this.expresses.length)];
    };
    async postReply(userID, commentID, replyContent) {
        if (!this.userID || !this.liveStreamID)
            return;
        var data = {
            liveStreamId: this.liveStreamID,
            replyContent: replyContent,
            commentId: commentID,
            fromUserId: userID
        };
        var { status, data } = await this.asyPost('https://zs.kwaixiaodian.com/rest/pc/live/assistant/comment/reply', data);
        console.log(status, data);
    };
    async postComment(commentContent) {
        if (!this.userID || !this.liveStreamID)
            return;

        var data = {
            liveStreamId: this.liveStreamID,
            commentContent: commentContent
        };
        console.log(new Date(), data);
        var { status, data } = await this.asyPost('https://zs.kwaixiaodian.com/rest/pc/live/assistant/comment/publish', data);
        console.log(status, data);
    };
    getReplyContent(content) {
        for (let reply of this.replyConfig.replies) {
            for (let keyWord of reply.keyWords) {
                if (content.includes(keyWord))
                    return reply.replyContent;
            }
        }
        return null;
    };
    checkReply(value) {
        let key = Object.keys(value).find(key => key.indexOf('__reactProps') == 0);
        if (!key)
            return;
        value = value[key].children.props.data;
        //首先查看是不是自己发出的，如果是自己发出的，就不管了
        let userName = value.fromUserName;
        let userID = value.fromUserId;
        console.log(userID, this.userID, userName);
        if (!userID || this.userID == userID)
            return;
        let commentID = value.commentId;
        if (Math.floor(commentID) <= Math.floor(localStorage.getItem('commentID'))) {
            console.log(commentID, Math.floor(localStorage.getItem('commentID')));
            return;
        }

        localStorage.setItem('commentID', commentID);
        //如果不相同的话，则需要匹配回复
        let commentContent = value.commentContent;
        //开始计算回复内容
        console.log("提问", userName, commentContent);
        let replyContent = this.getReplyContent(commentContent);
        console.log("回复", replyContent);
        //查询是否有对应的内容
        //查询是否有对应的内容
        if (!replyContent) {
            if (this.replyConfig.isFailLog) {
                JSCallWriteFail(commentContent);
            }
            return;
        }
        else {
            if (this.replyConfig.isSuccessLog) {
                JSCallWriteSuccess(commentContent, replyContent);
            }
        }
        let preReplyContent = "@";
        //是否加密名称
        if (this.replyConfig.isCodeNickName) {
            for (let i = 0; i < userName.length; i++)
                preReplyContent += '*';
        }
        else
            preReplyContent += userName;
        //是否需要切断
        if (this.replyConfig.isCutNickName) {
            let overReplyLength = preReplyContent.length + 1 + replyContent.length - this.commentMaxSize;
            if (overReplyLength > 0) {
                if (overReplyLength < preReplyContent.length - 2) {
                    preReplyContent = preReplyContent.substr(0, preReplyContent.length - overReplyLength);
                    replyContent = preReplyContent + " " + replyContent;
                }
            }
            else
                replyContent = preReplyContent + " " + replyContent;
        }
        else {
            replyContent = preReplyContent + " " + replyContent;
            if (replyContent.length > this.commentMaxSize)
                replyContent = replyContent.substr(0, this.commentMaxSize);
        }

        this.postReply(userID, commentID, replyContent);
    };
    async startReply(config) {
        if (this.replyObserver)
            return;
        console.log('开启客服');
        console.log(config);
        this.replyConfig = config;
        while (true) {
            if (document.querySelector('div.ReactVirtualized__Grid__innerScrollContainer'))
                break;
            await this.asySleep(100);
        }
        console.log('开启监听');
        document.querySelector('div.ReactVirtualized__Grid__innerScrollContainer').children.forEach((value) => {
            this.checkReply(value);
        });
        //开启监听
        this.replyObserver = new MutationObserver((mutationsList, observer) => {
            // 对变动进行处理
            for (let mutation of mutationsList) {
                if (mutation.type === 'childList') {
                    console.log(mutation.addedNodes.length);
                    mutation.addedNodes.forEach((value) => {
                        this.checkReply(value);
                    });
                }
            }
        });
        this.replyObserver.observe(document.querySelector('div.ReactVirtualized__Grid__innerScrollContainer'), { childList: true });
    };
    stopReply() {
        if (!this.replyObserver)
            return;
        console.log('关闭客服');
        this.replyObserver.disconnect();
        this.replyObserver = null;
    };
    startComment(config) {
        if (this.commentTimer)
            return;
        console.log('开启场控');
        console.log(config);
        this.commentConfig = config;
        if (this.commentConfig.isRandSort)
            this.commentConfig.comments.sort(() => Math.random() - 0.5);
        this.commentConfig.nowIndex = 0;
        if (this.commentConfig.comments.length == 0)
            return;
        this.startCommentTimer();
    };
    startCommentTimer() {
        this.commentTimer = setInterval(async () => {
            var commentContent = this.commentConfig.comments[this.commentConfig.nowIndex++];

            //1到2个表情包
            if (this.commentConfig.isRandPlace) {
                var randExpressNum = Math.floor(Math.random() * 2) + 1;
                for (var i = 0; i < randExpressNum; i++) {
                    var express = this.randExpress();
                    if (commentContent.length + express.length > this.commentMaxSize)
                        break;
                    commentContent += express;
                }
            }
            this.postComment(commentContent);

            if (this.commentConfig.nowIndex >= this.commentConfig.comments.length) {
                clearInterval(this.commentTimer);
                this.commentTimer = null;
                console.log(new Date(), '一轮结束，等待', this.commentConfig.turnWaitTime, '秒');
                this.startCommentTurnTimer();
            }
        }, this.commentConfig.waitTime * 1000);
    };
    startCommentTurnTimer() {
        this.commentTimer = setInterval(async () => {
            clearInterval(this.commentTimer);
            this.commentConfig.nowIndex = 0;
            console.log(new Date(), '一轮开始，等待', this.commentConfig.waitTime, '秒');
            this.startCommentTimer();
        }, this.commentConfig.turnWaitTime * 1000);
    };
    stopComment() {
        if (!this.commentTimer)
            return;
        console.log('关闭场控');
        clearInterval(this.commentTimer);
        this.commentTimer = null;
    };
};

var dwHelper = new DWHelper();
dwHelper.initData();

